<template>
  <!-- 原有的表单元素 -->
  <el-form-item label="年级:" prop="level">
    <el-select 
      v-model="ruleForm.level" 
      style="width: 200px" 
      clearable 
      placeholder="请选择年级"
      @change="handleGradeChange"
      :loading="loading"
    >
      <el-option 
        v-for="item in levelStore.list"
        :key="item.value"
        :label="item.name"
        :value="item.value"
      />
    </el-select>
  </el-form-item>

  <el-form-item label="学科:" prop="subject">
    <el-select 
      v-model="ruleForm.subject" 
      style="width: 200px" 
      clearable 
      placeholder="请选择学科"
      :disabled="!ruleForm.level"
      :loading="loading"
    >
      <el-option 
        v-for="subject in filteredSubjects"
        :key="subject.id"
        :label="subject.name"
        :value="subject.id"
      />
    </el-select>
  </el-form-item>

  <el-form-item label="题干:">
    <el-input v-model="questionTitle" placeholder="请输入题干" clearable style="width: 200px" @clear="" />
  </el-form-item>

  <el-form-item label="选项:">
    <div v-for="(option, index) in options" :key="index" style="display: flex; align-items: center; margin-bottom: 10px;">
      {{ String.fromCharCode(65 + index) }}
      <div style="width: 10px;"></div>
      <el-input v-model="option.shortValue" clearable style="width: 35px" @clear="" />
      <div style="width: 10px;"></div>
      <el-input v-model="option.longValue" clearable style="width: 500px" @clear="" />
    </div>
    <div style="width: 100%;"></div>
  </el-form-item>

  <el-form-item label="解析:">
    <el-input v-model="analysis" placeholder="请输入解析" clearable style="width: 600px" @clear="" />
  </el-form-item>

  <el-form-item label="分数:">
    <el-input-number v-model="num" :precision="1" :step="0.1" :max="10" />
  </el-form-item>

  <el-form-item label="难度:">
    <el-rate v-model="value" clearable />
  </el-form-item>

  <el-form-item label="正确答案:">
    <div>
      <template v-if="questionType === 1">
        <el-radio-group v-model="singleAnswer">
          <el-radio v-for="(option, index) in options" :key="index" :label="option.shortValue">{{ option.shortValue }}</el-radio>
        </el-radio-group>
      </template>
      <template v-else>
        <el-checkbox-group v-model="multipleAnswers">
          <el-checkbox v-for="(option, index) in options" :key="index" :label="option.shortValue">{{ option.shortValue }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </div>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitQuestion">提交</el-button>
    <el-button type="" @click="resetForm">重置</el-button>
    <el-button type="success" @click="addOption">添加选项</el-button>
    <el-button type="success" @click="openPreviewDialog">预览</el-button>
  </el-form-item>

  <!-- 预览组件 -->
  <Zujian ref="previewDialogRef">
    <template #content>
      <h4>选项:</h4>
      <div v-for="(option, index) in options" :key="index">
        {{ String.fromCharCode(65 + index) }}. {{ option.longValue }}
      </div>
    </template>
  </Zujian>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useLevelStore } from '@/stores/level'
import { getSubjectList, type Subject, editQuestion, getQuestionDetail } from '@/api/juanti'
import Zujian from './Zujian.vue'
import { useRoute } from 'vue-router'

const levelStore = useLevelStore()
const loading = ref(false)
const subjectList = ref<Subject[]>([])
const filteredSubjects = ref<Subject[]>([])
const ruleForm = reactive({
  level: null as number | null,
  subject: null as number | null
})

const route = useRoute()

// 复用相同的加载和筛选逻辑
const loadSubjects = async () => {
  try {
    loading.value = true
    const response = await getSubjectList()
    if (response?.code === 1 && Array.isArray(response?.response)) {
      subjectList.value = response.response
      filterSubjects()
    }
  } catch (error) {
    console.error('加载学科列表失败:', error)
  } finally {
    loading.value = false
  }
}

const filterSubjects = () => {
  if (ruleForm.level) {
    filteredSubjects.value = subjectList.value
      .filter(item => item.level === ruleForm.level)
  } else {
    filteredSubjects.value = []
  }
}

const handleGradeChange = () => {
  filterSubjects()
  ruleForm.subject = null
}

// 加载题目数据
const loadQuestionData = async (id: number) => {
  try {
    const response = await getQuestionDetail(id)
    if (response.code === 1 && response.response) {
      const data = response.response
      
      ruleForm.level = data.gradeLevel
      ruleForm.subject = data.subjectId
      questionTitle.value = data.title
      analysis.value = data.analyze
      num.value = parseFloat(data.score)
      value.value = data.difficult
      
      // 处理选项
      if (data.items && data.items.length > 0) {
        options.value = data.items.map((item: any, index: number) => ({
          shortValue: item.prefix || String.fromCharCode(65 + index),
          longValue: item.content
        }))
      }
      
      // 处理正确答案
      if (data.questionType === 1) {
        singleAnswer.value = data.correct
      } else {
        multipleAnswers.value = data.correct.split('')
      }
    }
  } catch (error) {
    console.error('加载题目失败:', error)
  }
}

onMounted(() => {
  loadSubjects()
  
  // 如果是编辑模式，加载题目数据
  const questionId = route.query.id as string
  if (questionId) {
    loadQuestionData(parseInt(questionId))
  }
})

const num = ref(0)
const value = ref(3)
const questionTitle = ref('')
const analysis = ref('')

// 存储选项的数组
const options = ref([
  { shortValue: 'A', longValue: '' },
  { shortValue: 'B', longValue: '' },
  { shortValue: 'C', longValue: '' },
  { shortValue: 'D', longValue: '' }
])

// 题目类型，1 为单选题，2 为多选题
const questionType = ref(2)
const singleAnswer = ref('A')
const multipleAnswers = ref(['A'])

// 添加选项的方法
const addOption = () => {
  const newIndex = options.value.length
  const newOption = {
    shortValue: String.fromCharCode(65 + newIndex),
    longValue: ''
  }
  options.value.push(newOption)
}

const previewDialogRef = ref<InstanceType<typeof Zujian>>()

// 打开预览对话框
const openPreviewDialog = () => {
  if (previewDialogRef.value) {
    previewDialogRef.value.openDialog()
  } else {
    console.error('预览对话框引用未定义')
  }
}

const resetForm = () => {
  location.reload() // 刷新页面实现重置
}

// 提交题目
const submitQuestion = async () => {
  try {
    const correct = questionType.value === 1 ? singleAnswer.value : multipleAnswers.value.join('')
    const params = {
      id: route.query.id ? parseInt(route.query.id as string) : 0,
      questionType: questionType.value,
      subjectId: ruleForm.subject || 0,
      title: questionTitle.value,
      gradeLevel: ruleForm.level || 0,
      items: options.value.map(option => ({ prefix: option.shortValue, content: option.longValue })),
      analyze: analysis.value,
      correctArray: null,
      correct,
      score: num.value,
      difficult: value.value,
      itemOrder: null
    }
    const response = await editQuestion(params)
    if (response.code === 1) {
      console.log('提交成功')
    } else {
      console.error('提交失败:', response.message)
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}
</script>